import styles from "./home.module.css"
import { Space, Input, ConfigProvider, Button, Avatar, Dropdown, Result, Image } from "antd"
import { SearchOutlined } from '@ant-design/icons'
import { UserOutlined, MessageOutlined } from '@ant-design/icons';
import React, { useEffect } from 'react'
import type { GetProps } from "antd"
import type { MenuProps } from 'antd';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';
import { Loading } from '../../components/loading'
import { useState, useRef } from "react";
import { selectPost,getViewIncr } from "../../api/post";
import { getForumPageList } from "../../api/forum";

function Home() {
    return (
        <div>
            <div className="bodyContent">
                {/* 顶部 */}
                <HeaderNav title="轻奢贴吧" />

                <div className={styles.bodyHome}>
                    <div className={styles.homeTop}>
                        <div className={styles.carousel}>
                            <img src="../../static/lb1.png" alt="" />
                        </div>
                        <div className={styles.hot}>
                            <h3 style={{ margin: '0 0 10px 0' }}>| 热门贴吧</h3>
                            <div style={{ flex: '1', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                                {circleList()}
                            </div>
                        </div>
                    </div>
                </div>

                <div className={styles.bodyTopic}>
                    <div className={styles.topicLeft}>
                        {leftHome()}
                    </div>
                    <div className={styles.topicCenter}>
                        <CenterHome />
                    </div>
                    <div className={styles.topicRight}>
                        {rightHome()}
                    </div>
                </div>

                <div className={styles.bodyFoolter}>
                    <div></div>
                </div>
            </div>
        </div>
    )
}

// 头部导航栏
function HeaderNav({ title }: { title: string }) {
    const isProfilePage = title === "个人中心";
    return (
        <div className={styles.bodyHeader}>
            {bodyLeftTool(title)}
            {!isProfilePage && bodySearchTool()}
            {bodyRightTool()}
        </div>
    );
}


// 定义数据接口
interface circleUser {
    id: number,
    name?: string,
    followers?: number;
    messages?: number;
    avatar?: string; // 可选的用户头像URL
}

function circleList() {

    getForumPageList({ startPage: 1, endPage: 10 }).then(res => {
        console.log(res);
    })

    const [userList, setUserList] = React.useState<circleUser[]>([
        { id: 1, name: '湖北师范大学1111111111111111', followers: 123, messages: 321 },
        { id: 2, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 3, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 4, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 5, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 6, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 7, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 8, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 9, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 10, name: '湖北师范大学', followers: 123, messages: 321 },
        { id: 11, name: '湖北师范大学', followers: 123, messages: 321 },
    ]);

    return (
        <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {
                userList.map((user) => (
                    <div
                        key={user.id}
                        className={styles.circleUser}
                    >
                        <div style={{ display: 'flex', alignItems: 'center', overflow: 'hidden' }}>
                            <Avatar size={60} icon={<UserOutlined />} style={{ flexShrink: 0 }} />
                            <div style={{ minWidth: 0 }}>
                                <p style={{ fontSize: '15px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.name}</p>
                                <p style={{ fontSize: '12px' }}><UserOutlined /> {user.followers}</p>
                                <p style={{ fontSize: '12px' }}><MessageOutlined /> {user.messages}</p>
                            </div>
                        </div>
                    </div>
                ))
            }


        </div>
    );
}

function leftHome() {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    console.log(user);
    return (
        <div>
            <div>
                <p>个人信息</p>
                <div className={styles.userInfo}>
                    <Avatar shape="square" size={80} icon={<UserOutlined />} style={{ flexShrink: 0 }} />
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '7px' }}>
                        <p>昵称：{user.nickname}</p>
                        <p>性别：{user.gender == 1 ? '男' : '女'}</p>
                        <p>出生年月：{user.birthDate}</p>
                    </div>
                </div>
            </div>

            <div>
                <p style={{ color: '#e4e4e4' }}>个人简介</p>
                <div className={styles.userInfo}>
                    <p>{user.profile}</p>
                </div>
            </div>

            {/* <div>
                <p style={{ color: '#e4e4e4' }}>加入的吧</p>
                <div style={{ width: '100%', boxSizing: 'border-box', padding: '50px 0', display: 'flex', justifyContent: 'center', color: 'yellow' }}>
                    <p>正在开发中，敬请等待~(⌐■_■)</p>
                </div>
            </div>

            <div>
                <p style={{ color: '#e4e4e4' }}>贴吧分类</p>
                <div style={{ width: '100%', boxSizing: 'border-box', padding: '50px 0', display: 'flex', justifyContent: 'center', color: 'yellow' }}>
                    <p>正在开发中，敬请等待~(⌐■_■)</p>
                </div>
            </div> */}
        </div>

    )
}

function rightHome() {
    let hotList = [
        {
            sort: 1,
            name: '又有人被抓了',
            url: 'https://www.baidu.com',
            hot: 62843
        },
        {
            sort: 2,
            name: '特朗普关税政策',
            url: 'https://www.baidu.com',
            hot: 59836
        },
        {
            sort: 3,
            name: '破碗不干人事',
            url: 'https://www.baidu.com',
            hot: 55236
        }, {
            sort: 4,
            name: '乔绾是大蠢猪',
            url: 'https://www.baidu.com',
            hot: 51691
        }, {
            sort: 5,
            name: '破碗不干人事',
            url: 'https://www.baidu.com',
            hot: 49826
        }, {
            sort: 6,
            name: '破碗不干人事',
            url: 'https://www.baidu.com',
            hot: 48926
        },
    ]
    return (
        <>
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between' }}>
                <p>贴吧热搜</p>
                <p>点击刷新</p>
            </div>
            {

                hotList.map((res, index) => (
                    <div key={index} className={styles.hotList}>
                        <p><span>{res.sort}、</span>{res.name}</p>
                        <p>浏览量<span>{res.hot}</span></p>
                    </div>
                ))
            }
        </>
    )
}

function CenterHome() {
    const [postList, setPostList] = useState<any[]>([]);
    useEffect(() => {
        selectPost().then((res) => {
            setPostList(res.data)
        })
    }, [])
    console.log(postList);
    if (postList.length === 0) {
        return (
            <div style={{ width: '100%', boxSizing: 'border-box', padding: '50px 0', display: 'flex', justifyContent: 'center'}}>
                <p>正在加载中，请稍等~</p>
            </div>
        ) 
    }

    return <PostCard list={postList} />
}

function PostCard({ list }: { list: any[] }) {
    dayjs.extend(relativeTime);
    dayjs.locale('zh-cn');
    console.log('upload url', process.env.PUBLIC_UPLOAD_URL);
    const imgUrl = process.env.PUBLIC_UPLOAD_URL;
    const navigate = useNavigate()
    
    return (
        <div>
            {
                list.map((res, index) => (
                    <div key={index} className={styles.postCard} onClick={async() => {
                        await getViewIncr(res.postId)
                        navigate('/post', {state: {postId:res.postId}})}
                    }>
                        <div className={styles.postCardHeader}>
                            <div style={{ display: "flex", flexDirection: "row", gap: "10px" }}>
                                <Avatar size={45} src={imgUrl + res.user.avatar} />
                                <div className={styles.postCardHeaderLeft}>
                                    <div style={{ display: "flex", flexDirection: "row", gap: "10px" }}>
                                        <p>{res.user.nickname}</p>
                                        <p>{res.gender == "1" ? "男" : "女"}</p>
                                    </div>
                                    <p style={{ fontSize: "12px" }}>{dayjs(res.createTime).fromNow()}</p>
                                </div>
                            </div>
                            <div>
                                <p>{res.forumName}</p>
                                <p>{res.category}</p>
                            </div>
                        </div>
                        <div className={styles.postCardContent}>
                            <p style={{ fontSize: "18px", fontWeight: "bold" }}>{res.postTitle}</p>
                            <div dangerouslySetInnerHTML={{ __html: res.postContent }}></div>
                            <div style={{ display: "flex", gap: "10px" }} onClick={(e) => e.stopPropagation()}>
                                {JSON.parse(res.postImages).map((res: string, index: number) => (
                                    <Image key={index} src={imgUrl + res} width={100} height={100} ></Image>
                                ))}
                            </div>
                        </div>
                        <div className={styles.postCardFooter}>
                            <p>浏览量<span>{res.viewCount}</span></p>
                            <p>评论量<span>{res.commentCount}</span></p>
                            <p>点赞量<span>{res.likeCount}</span></p>
                        </div>
                    </div>
                ))
            }
        </div>
    )
}
function bodyLeftTool(title: string) {
    const toolLeft = [
        {
            name: title
        }
    ]
    return (
        <div className='direction_row' >
            {toolLeft.map((res, index) => (
                <div className={styles.header_card} key={index}>{res.name}</div>
            ))}
        </div>
    )
}

function bodyRightTool() {
    const navigate = useNavigate()
    const items: MenuProps['items'] = [
        {
            key: '1',
            label: <span onClick={() => {
                navigate('/user')
            }}>个人中心</span>
        },
        {
            key: '2',
            label: <span onClick={() => {
                localStorage.removeItem('user')
                navigate('/')
            }}>退出登录</span>
        }
    ]

    // 发布
    const handPostClick = () => {
        navigate('/addPost')
    }

    return (
        <div className='direction_row' >
            <Dropdown menu={{ items }} placement="bottom">
                <div className={styles.header_card}>
                    <a>我的</a>
                </div>
            </Dropdown>
            <div className={styles.header_card} onClick={handPostClick}>发帖</div>
        </div>
    )
}

function bodySearchTool() {
    const { Search } = Input;
    type SearchProps = GetProps<typeof Input.Search>
    const [loadingBoolean, setLoadingBoolean] = useState(false)
    const navigate = useNavigate()
    const onSearch: SearchProps['onSearch'] = (value, _e, info) => {
        setLoadingBoolean(true)
        setTimeout(() => {
            console.log(info?.source, value);
            navigate(`/search?keyword=${value}`)
            setLoadingBoolean(false)
        }, 1000)
    }



    return (
        <div>
            <Loading loading={loadingBoolean} />
            <ConfigProvider
                theme={{
                    components: {
                        Input: {
                            colorBgContainer: 'rgba(0,0,0,0)',
                            activeBg: 'rgb(255, 255, 255)',
                        }
                    }
                }}>
                <Space >
                    <Search className={styles.custom_placeholder_input} onSearch={onSearch} style={{ maxWidth: '500px' }}
                        enterButton={
                            <Button
                                style={{ backgroundColor: 'rgba(0,0,0,0)', color: '#fff' }}
                                icon={<SearchOutlined style={{ color: 'white' }} />}
                            // onClick={handleSearch}
                            />
                        } ></Search>
                </Space>
            </ConfigProvider>
        </div>
    )
}

export { Home as default, HeaderNav, PostCard };
